package cn.dzhang.rcp.hyperbola.actions;

import org.eclipse.jface.action.ContributionItem;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;

/**
 * 填充的分割器，将右边的控件一直撑到底
 * 
 * @author dzhang
 * @since 2015-8-10
 */
public class FillSeparator extends ContributionItem {
	private final int width;

	/**
	 * 右边预留的宽度
	 * 
	 * @param width
	 */
	public FillSeparator(int width) {
		super();
		this.width = width;
	}

	/*
	 * (non-Javadoc) Method declared on IContributionItem. Fills the given menu
	 * with a SWT separator MenuItem.
	 */
	@Override
	public void fill(Menu menu, int index) {
		if (index >= 0) {
			new MenuItem(menu, SWT.SEPARATOR, index);
		} else {
			new MenuItem(menu, SWT.SEPARATOR);
		}
	}

	@Override
	public void fill(ToolBar toolbar, int index) {
		ToolItem item;
		if (index >= 0) {
			item = new ToolItem(toolbar, SWT.SEPARATOR, index);
		} else {
			item = new ToolItem(toolbar, SWT.SEPARATOR);
		}

		toolbar.addControlListener(new ToolBarResizeListener(item, width));
	}

	@Override
	public boolean isSeparator() {
		return true;
	}

	private static class ToolBarResizeListener extends ControlAdapter {
		private final ToolItem toolItem;
		private final int width;

		public ToolBarResizeListener(ToolItem toolItem, int width) {
			this.toolItem = toolItem;
			this.width = width;
		}

		@Override
		public void controlResized(ControlEvent e) {
			ToolBar toolBar = (ToolBar) e.widget;
			toolItem.setWidth(toolBar.getSize().x - toolItem.getBounds().x
					- width);
		}
	};
}
